package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.nio.charset.StandardCharsets;

public class EchoHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        try (PrintWriter writer = new PrintWriter(response)) {
            Map<String, String> params = request.getAllParams();

            StringBuilder contentBuilder = new StringBuilder();
            contentBuilder.append("<h1>Echo Server Response</h1>");
            contentBuilder.append("<h2>Request Details:</h2>");
            contentBuilder.append("<p>Method: ").append(request.getMethod()).append("</p>");
            contentBuilder.append("<p>URL: ").append(request.getUrl()).append("</p>");

            // TODO: [222024321072027/舒鑫]根据接收到的参数Map构建HTML列表，回显给客户端
            if (params.isEmpty()) {
                contentBuilder.append("<h2>No Parameters Received.</h2>");
            } else {
                contentBuilder.append("<h2>Received Parameters:</h2>");
                contentBuilder.append("<ul>");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    contentBuilder.append("<li><strong>").append(entry.getKey())
                            .append("</strong>: ").append(entry.getValue()).append("</li>");
                }
                contentBuilder.append("</ul>");
            }

            String content = contentBuilder.toString();

            // TODO: [222024321072027/舒鑫] 构造完整的 HTTP 响应头
            writer.println("HTTP/1.1 200 OK");
            writer.println("Content-Type: text/html; charset=UTF-8");
            // 使用StandardCharsets指定编码计算长度
            writer.println("Content-Length: " + content.getBytes(StandardCharsets.UTF_8).length);
            writer.println("Connection: close");
            writer.println();
            writer.println(content);
            writer.flush();
        } catch (Exception e) {
            System.err.println("EchoHandler处理异常: " + e.getMessage());
            // 发送500错误响应
            try (PrintWriter writer = new PrintWriter(response)) {
                String errorMsg = "<h1>500 Internal Server Error</h1><p>Error in EchoHandler</p>";
                writer.println("HTTP/1.1 500 Internal Server Error");
                writer.println("Content-Type: text/html; charset=UTF-8");
                writer.println("Content-Length: " + errorMsg.getBytes(StandardCharsets.UTF_8).length);
                writer.println();
                writer.println(errorMsg);
                writer.flush();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}